package com.jjty.dataGenerator.jserji.controller;

import com.jjty.dataGenerator.common.ApiResult;
import com.jjty.dataGenerator.jserji.service.JsDataGeneratorService;
import com.jjty.dataGenerator.jserji.service.JsDataReportService;
import com.jjty.dataGenerator.jserji.service.SchoolNameService;
import com.jjty.dataGenerator.jserji.service.StudentNumberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/data/js")
public class JsDataController {

    @Autowired
    private JsDataGeneratorService jsDataGeneratorService;
    @Autowired
    private JsDataReportService jsDataReportService;
    @Autowired
    private SchoolNameService schoolNameService;
    @Autowired
    private StudentNumberService studentNumberService;

    @RequestMapping("/generateData")
    public ApiResult generateData(@RequestParam String dataType, Integer numRecords) {
        try {
            if (numRecords == null || numRecords <= 0) {
                return ApiResult.doFailure("记录数量必须为正整数");
            }
            jsDataGeneratorService.generateData(dataType, numRecords);
            return ApiResult.doSuccess("随机数据生成并保存成功");
        } catch (IllegalArgumentException e) {
            log.warn("无效的dataType: {}", dataType);
            return ApiResult.doFailure(e.getMessage()); // 返回具体错误信息
        } catch (IllegalStateException e) {
            log.error("生成数据失败: {}", e.getMessage());
            return ApiResult.doFailure(e.getMessage());
        } catch (Exception e) {
            log.error("数据生成失败", e);
            return ApiResult.doFailure("数据生成失败，请联系管理员");
        }
    }

    @RequestMapping("/reportData")
    public ApiResult reportData(String dataType,String url){
        try{
            jsDataReportService.reportData(dataType,url);
        }catch (Exception e){
            e.printStackTrace();
            return ApiResult.doFailure(e.getMessage());
        }
        return ApiResult.doSuccess("上报成功");
    }

    @PostMapping("/fillSchoolNames")
    public String fillSchoolNames(@RequestParam String schoolName, @RequestParam int numRecords) {
        int count = schoolNameService.fillSchoolNames(schoolName, numRecords);
        return String.format("成功填充 %d 条记录的学校名称为 %s", count, schoolName);
    }

    @PostMapping("/fillStudentNumber")
    public String fillStudentNumber() {
        studentNumberService.fillStudentNumber();
        return "StudentNumber 填充完成！";
    }
    @PostMapping("/fillOtherData")
    public String fillOtherFields() {
        studentNumberService.fillStudentFields();
        return "年级、班级、亲属关系、性别填充完成！";
    }
}